<template>
    <view class="buddyList">
        <view class="search-view">
            <u-search :show-action='false' placeholder="搜索" v-model="search" @search="searchFn"></u-search>
        </view>
        <view class="structure">
            <view class="structure-item" :style="{
				 color:index !== structures.length-1 ? '#0086FE':'#888'
			 }" v-for="(structure,index) in structures"
                  :key="structure" @click="changeStrcure(index)">
                {{ structure }}
                <template v-if="index !== structures.length-1">
                    >
                </template>
            </view>
        </view>

        <view class="contact-list">
            <view class="department" v-if="department.length">
                <u-checkbox-group :max="max" :value="selectContact" width="100%" shape="circle" :wrap="true">
                    <u-checkbox v-model="it.checked"
                                v-for="(it,index) in department"
                                warp
                                @change="checkboxChange(it,$event)"
                                :key="it.id" :name="it.id">
                        <view class="department-item">
                            {{ it.name }}
                            <view class="pull-right" v-if="it.children.length"
                                  @click.stop="departmentClickHandle(it,index)">
                                <u-icon style="margin-right: 20rpx;" name="list"></u-icon>
                                下级
                            </view>
                        </view>
                    </u-checkbox>
                </u-checkbox-group>
            </view>

        </view>

        <view class="float-bar">
            <view class="contact-count">
                <view @click="showPupUp" v-if="selectContact.length"> {{ selectText }}
                    <u-icon name="arrow-up"></u-icon>
                </view>
            </view>
            <view class="confirm-button">
                <u-button ripple type="primary" @click="confirmFn">确定({{ selectContact.length }})</u-button>
            </view>
        </view>

        <uni-popup ref="popup" type="bottom">
            <view class="uni-share-title">
                <text class="uni-share-title-text">已选择的部门</text>
            </view>
            <scroll-view scroll-y class="department" style="max-height: 40vh;border-bottom: 0;">
                <template v-for="it in selectContact">
                    <u-checkbox shape="circle" style="width: 100%" warp v-model="it.checked" :name="it.id"
                                @change="checkboxChange(it,$event)">
                        <view class="department-item">
                            <view class="user-info">
                                {{it.name}}
                            </view>
                        </view>
                    </u-checkbox>
                </template>
            </scroll-view>
        </uni-popup>
    </view>
</template>

<script>
    import UButton from "../../uview-ui/components/u-button/u-button";
    import UIcon from "../../uview-ui/components/u-icon/u-icon";
    import {
        toTreeData
    } from "../../utils/util";
    import UCheckboxGroup from "../../uview-ui/components/u-checkbox-group/u-checkbox-group";
    import UCheckbox from "../../uview-ui/components/u-checkbox/u-checkbox";
    import USearch from "../../uview-ui/components/u-search/u-search";

    export default {
        components: {
            USearch,
            UCheckbox,
            UCheckboxGroup,
            UIcon,
            UButton
        },
        data() {
            return {
                search: '',
                treeData: [],
                pageIndex: [0],
                personnel: [],
                selectContactMap: new Map(),
                selectContact: [],
                selModel: 0,
                searchData: []
            }
        },
        watch: {
            'selectContact.length'(val) {
                if (val === 0) {
                    this.$refs.popup.close()
                }
                this.initChecked()
            }
        },
        computed: {
            getTreeData() {
                return toTreeData(this.treeData, {
                    id: 'id',
                    parendId: 'pId',
                    name: 'name',
                    rootId: ''
                })
            },
            max() {
                return this.selModel === '0' ? 1 : 999
            },
            selectText() {
                if (this.selectContact.length) {
                    return `已选择${this.selectContact.length}人`
                } else {
                    return ''
                }
            },
            currentPage() {
                let currentPage = this.getTreeData;

                if (currentPage && currentPage.children) {
                    this.pageIndex.forEach(e => {
                        if (e === '搜索') {
                            currentPage = this.searchData
                        } else {
                            currentPage = currentPage.children[e]
                        }
                    })
                }
                return currentPage
            },
            department() {
                if (this.pageIndex[this.pageIndex.length - 1] === '搜索') {
                    return this.currentPage
                } else {
                    if (this.currentPage && this.currentPage.children) {
                        return this.currentPage.children
                    } else {
                        return []
                    }
                }
            },
            structures() {
                let structure = []
                let currentPage = this.getTreeData;

                if (currentPage && currentPage.children && currentPage.children.length) {
                    this.pageIndex.forEach(e => {
                        if (e === '搜索') {
                            structure.push('搜索')
                        } else {
                            currentPage = currentPage.children[e]
                            structure.push(currentPage.name)
                        }
                    })
                }
                return structure
            }
        },
        methods: {
            confirmFn() {
                const eventChannel = this.getOpenerEventChannel()
                eventChannel.emit('sendContactData', {
                    data: this.selectContact
                });
                uni.navigateBack()
            },
            initChecked() {
                let ids = this.selectContact.map(e => e.id)
                this.searchData = this.searchData.map(e => {
                    e.checked = ids.includes(e.id)
                    return e
                })
                this.searchData = this.searchData.map(e => {
                    e.checked = ids.includes(e.id)
                    return e
                })

            },
            async searchFn(value) {
                uni.showLoading({
                    mask: true,
                    title: '搜索中'
                })
                let res = await this.api.getOrgTree_query({
                    queryDep: value
                })
                if (this.pageIndex[this.pageIndex.length - 1] !== '搜索') {
                    this.pageIndex.push('搜索')
                }
                this.searchData = res.data.map(e => {
                    e.children = []
                    e.name = e.depName
                    return e
                })
                this.initChecked()
                uni.hideLoading()
            },
            showPupUp() {
                this.$refs.popup.open()
            },
            changeStrcure(index) {
                if (index === this.pageIndex.length - 1) return
                this.pageIndex.splice(index + 1, this.pageIndex.length - index)

            },
            checkboxChange(data, e) {
                if (this.selectContactMap.has(e.name)) {
                    this.selectContactMap.get(e.name).checked = false
                    this.selectContactMap.delete(e.name)
                } else {
                    this.selectContactMap.set(e.name, data)
                }
                this.selectContact = Array.from(this.selectContactMap).map(e => e[1])
            },
            departmentClickHandle(data, index) {
                this.pageIndex.push(index)
            },
            async fetchData(depIds) {
                uni.showLoading({
                    mask: true,
                    title: '加载中'
                })
                if (depIds) {
                    depIds = depIds.split(' ').join(';');
                }

                let data = await this.api.getOrgTree({});
                this.treeData = data.data.map(e => {
                    if (depIds && depIds.includes(e.id)) {
                        e.checked = true
                        this.selectContactMap.set(e.id, e)
                        this.selectContact.push(e)
                    } else {
                        e.checked = false
                    }
                    return e
                });
                uni.hideLoading()
            }
        },
        onLoad(options) {
            this.selModel = options.selModel
            this.idField = options.idField
            this.fetchData(options.depIds)
        }
    }
</script>

<style lang="less" scoped>
    .buddyList {
        background: #FFF;
        display: flex;
        flex-direction: column;
        height: 100vh;
        // padding: 20rpx 0 120rpx;
        /* #ifdef H5 */
        height: calc(100vh - 88rpx);

        /* #endif */

        .search-view {
            padding: 20rpx;
        }

        .structure {
            padding: 20rpx;
            display: flex;
            flex-wrap: wrap;
            border-bottom: 20rpx solid #EEE;
            line-height: 1.8;

        }

        .contact-list {

            flex: 1;
            overflow: scroll;


        }

        .department {
            padding: 0 20rpx;
            border-bottom: 20rpx solid #eee;

            .u-checkbox-group {
                width: 100%;
            }

            .department-item {
                font-size: 30rpx;
                border-bottom: 1px solid #eee;
                padding: 26rpx 0;
                position: relative;

                .pull-right {
                    right: 20rpx;
                    top: 50%;
                    transform: translateY(-50%);
                    position: absolute;
                    color: #0086FE;
                    border-left: 1rpx solid #eee;
                    padding-left: 20rpx;
                }
            }
        }


        .float-bar {
            border-top: 1px solid #eee;
            padding: 20rpx 20rpx calc(20rpx + var(--window-bottom)) 20rpx;
            align-items: center;
            display: flex;
            background: #FFF;
            width: 100%;
            justify-content: space-between;

            .contact-count {
                color: #0086FE;
            }
        }

        .uni-share-title {
            /* #ifndef APP-NVUE */
            display: flex;
            /* #endif */
            flex-direction: row;
            align-items: center;
            justify-content: center;
            height: 40px;
            border-bottom: 1px solid #eee;
        }

        .uni-share-title-text {
            font-size: 14px;
            color: #666;
        }
    }
</style>
